package common;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * 加载和获取spring上下文环境，支持xml文件配置方式和静态代码加载方式两种形式
 */
@Component
public class SpringContext implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(SpringContext.class);

    private static ApplicationContext context;

    public SpringContext() {
        logger.info("初始化ContextHolder..............................");
    }

    /**
     * spring配置文件加载方式
     *
     * @param context
     */
    public void setApplicationContext(ApplicationContext context) {
        SpringContext.context = context;
        logger.info("设置ApplicationContext...........................");
    }

    /**
     * 应用启动时静态加载方式
     *
     * @param context
     */
    public static void load(ApplicationContext context) {
        SpringContext.context = context;
        logger.info("设置ApplicationContext...........................");
    }

    /**
     * 获取spring上下文 ApplicationContext
     *
     * @return
     */
    public static ApplicationContext context() {
        if (context == null) {
            throw new IllegalStateException("context未注入，请在spring配置文件中定义SpringContext或者在应用启动时手动加载");
        }
        return context;
    }

    /**
     * 获取spring管理的bean
     *
     * @param name
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name) {
        return (T) context.getBean(name);
    }

    /**
     * 根据类型获取bean
     * 
     * @param clazz
     * @return
     */
    public static <T> T getBean(Class<?> clazz) {
        return (T) context.getBean(clazz);
    }


}
